'use client';

import { useState } from 'react';
import { zodResolver } from '@hookform/resolvers/zod';
import { useForm } from 'react-hook-form';
import * as z from 'zod';
import { Button } from '@/components/ui/button';
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from '@/components/ui/form';
import { Input } from '@/components/ui/input';
import { useToast } from '@/components/ui/use-toast';
import { Toaster } from 'sonner';
import { updateUserPassword } from '@/services/userService';
import { useRouter } from 'next/navigation';

const securityFormSchema = z.object({
  currentPassword: z.string().min(6, '密码至少6个字符'),
  newPassword: z.string().min(6, '密码至少6个字符'),
  confirmPassword: z.string().min(6, '密码至少6个字符'),
}).refine((data) => data.newPassword === data.confirmPassword, {
  message: '两次输入的密码不一致',
  path: ['confirmPassword'],
});

type SecurityFormValues = z.infer<typeof securityFormSchema>;

export function SecurityForm() {
  const [isLoading, setIsLoading] = useState(false);
  const { toast } = useToast();
  const router = useRouter();

  const form = useForm<SecurityFormValues>({
    resolver: zodResolver(securityFormSchema),
    defaultValues: {
      currentPassword: '',
      newPassword: '',
      confirmPassword: '',
    },
  });

  async function onSubmit(data: SecurityFormValues) {
    setIsLoading(true);
    try {
      console.log('提交密码修改:', data.currentPassword, data.newPassword);
      const success = await updateUserPassword(data.currentPassword, data.newPassword);
      console.log('密码修改结果:', success);
      
      if (success) {
        toast({
          title: '修改成功',
          description: '密码已更新，下次登录请使用新密码',
        });
        form.reset();
      } else {
        toast({
          title: '修改失败',
          description: '当前密码可能不正确',
          variant: 'destructive',
        });
      }
    } catch (error: any) {
      console.error('密码修改错误(详细):', error);
      
      // 显示详细的错误信息，不立即处理401
      let errorMessage = '未知错误';
      let errorTitle = '修改失败';
      
      if (error.response) {
        console.log('错误响应:', error.response);
        
        if (error.response.status === 500) {
          // 对于500错误，可能是服务器问题，但密码可能已经修改成功
          errorTitle = '服务器错误';
          errorMessage = '服务器处理请求时出错，但密码可能已经修改成功。请尝试使用新密码登录。';
          
          // 重置表单
          form.reset();
        } else {
          errorMessage = `状态码: ${error.response.status}, 消息: ${error.response.data?.message || '无消息'}`;
        }
      } else if (error.message) {
        errorMessage = error.message;
      }
      
      toast({
        title: errorTitle,
        description: errorMessage,
        variant: 'destructive',
      });
    } finally {
      setIsLoading(false);
    }
  }

  return (
    <>
      <Toaster />
      <Form {...form}>
        <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-6">
          <FormField
            control={form.control}
            name="currentPassword"
            render={({ field }) => (
              <FormItem>
                <FormLabel>当前密码</FormLabel>
                <FormControl>
                  <Input
                    placeholder="请输入当前密码"
                    type="password"
                    {...field}
                  />
                </FormControl>
                <FormMessage />
              </FormItem>
            )}
          />

          <FormField
            control={form.control}
            name="newPassword"
            render={({ field }) => (
              <FormItem>
                <FormLabel>新密码</FormLabel>
                <FormControl>
                  <Input
                    placeholder="请输入新密码"
                    type="password"
                    {...field}
                  />
                </FormControl>
                <FormMessage />
              </FormItem>
            )}
          />

          <FormField
            control={form.control}
            name="confirmPassword"
            render={({ field }) => (
              <FormItem>
                <FormLabel>确认新密码</FormLabel>
                <FormControl>
                  <Input
                    placeholder="请再次输入新密码"
                    type="password"
                    {...field}
                  />
                </FormControl>
                <FormMessage />
              </FormItem>
            )}
          />

          <Button type="submit" disabled={isLoading} className="w-full">
            {isLoading ? '修改中...' : '修改密码'}
          </Button>
        </form>
      </Form>
    </>
  );
} 